package com.asia5b.a5mall.order.activity

import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import android.text.TextUtils
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.config.Asia5bPayUtils
import com.asia5b.a5mall.middleware.event.AsiaPayEvent
import com.asia5b.a5mall.middleware.event.PayEvent
import com.asia5b.a5mall.middleware.logic.viewmodel.order.DiffOrderActivityVM
import com.asia5b.a5mall.middleware.model.base.ResultModel
import com.asia5b.a5mall.middleware.model.order.DiffDetailModel
import com.asia5b.a5mall.middleware.model.bean.DiffOrderMenuBean
import com.asia5b.a5mall.middleware.model.order.OrderPayModel
import com.asia5b.a5mall.middleware.model.order.TradeType
import com.asia5b.a5mall.middleware.model.shop.AbsGoodsModel
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.order.R
import com.asia5b.a5mall.order.adapter.DiffOrderPriceAdapter
import com.asia5b.a5mall.order.adapter.OrderParcelGoodsAdapter
import com.asia5b.a5mall.order.databinding.ActivityDifforderBinding
import kotlinx.android.synthetic.main.activity_difforder.*
import kotlinx.android.synthetic.main.item_difforder_address.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by zhangyuncai on 2020/3/23.
 * 差价付款
 */
@Route(path = ActCons.DiffOrderActivity)
class DiffOrderActivity : SimpleActivity<DiffOrderActivityVM, ActivityDifforderBinding>() {
    override val viewModelClazz: Class<DiffOrderActivityVM>
        get() = DiffOrderActivityVM::class.java

    override fun getDataBinding(): ActivityDifforderBinding {
        return ActivityDifforderBinding.inflate(layoutInflater)
    }

    override var sIsDark = true

    var orderId = 0

    val goods = arrayListOf<AbsGoodsModel>()
    val goodsRecyclerView by lazy { rv_orderplace_goods }
    val goodsAdapter = OrderParcelGoodsAdapter(goods)

    val priceRecyclerView by lazy { rv_orderplace_price }

    var detailModel: DiffDetailModel? = null

    val goodsActivityCallBack = {
        push(ActCons.PlaceGoodListActivity, {
            it.withSerializable("datas", goods)
        })
    }


    override fun initView() {
        goodsRecyclerView.run {
            layoutManager = GridLayoutManager(mActivity, 4)!!
            adapter = goodsAdapter
        }
        orderId = intent.getIntExtra("id", 0)
        mViewModel.getDiffDetail(orderId)
    }


    override fun initEvent() {
        bt_orderplace_submit.setOnClickListener {
            detailModel?.run {
                val charge = cost_charge?.charge ?: 0.0
                Asia5bPayUtils.getAuthorization(mActivity, true) { isCanSkip ->
                    if (isCanSkip) {
                        mViewModel.startPay(orderId, charge)

                    }
                }
            }

        }
        cons_difforder_goods.setOnClickListener {
            goodsActivityCallBack.invoke()
        }
        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            goodsActivityCallBack.invoke()
        }
    }

    override fun startObserver() {
        mViewModel.startPayResultLiveData.observe(mActivity, Observer {
            startPayResult(it[0] as ResultModel<String>, it[1] as Double)
        })
        mViewModel.getDiffDetailResultLiveData.observe(this, Observer {
            getDiffDetailResult(it)
        })
    }

    override fun initData() {

    }

    fun getDiffDetailResult(detailModel: DiffDetailModel) {
        this.detailModel = detailModel
        detailModel.run {
            //设置地址
            tv_order_addressname.text = "${ship_name} ${ship_tel}"
            tv_order_addressdetail.text = "${address_name}"

            //订单号
            tv_orderparcel_ordersn.text = "${order_sn}"
            var goodsNum = 0
            express_list?.forEach {
                it.goods_list?.run {
                    goods.addAll(this)
                    goodsNum += (this.size)
                }
            }
            var texts = String.format(getString(R.string.共_数_件商品), "${goodsNum}")
            val spanText = StringUtils.setTextColor(texts, "${goodsNum}", ContextCompat.getColor(mActivity, R.color.common_text_blue))
            tv_orderparcel_ordergoodsnum.setText(spanText)
            goodsAdapter.notifyDataSetChanged()

            //价格详情
            val priceList = arrayListOf<DiffOrderMenuBean>()
            priceList.add(DiffOrderMenuBean().run {
                typetag = "订单编号"
                type = getString(R.string.售后单号)
                value = "${order_sn}"
                this
            })
            priceList.add(DiffOrderMenuBean().run {
                typetag = "下单时间"
                type = getString(R.string.下单时间)
                val create_time = WTimeUtils.format("${create_time * 1000}", WTimeUtils.text_yyyy_MM_dd_HH_mm_ss)
                value = "${create_time}"
                this
            })
            priceList.add(DiffOrderMenuBean().run {
                typetag = "国际运费"
                type = getString(R.string.国际运费)
                value = cost_international_charge
                valueOption = international_charge
                this
            })
            priceList.add(DiffOrderMenuBean().run {
                typetag = "国内运费"
                type = getString(R.string.国内运费)
                value = cost_local_charge
                valueOption = local_charge
                this
            })
            priceList.add(DiffOrderMenuBean().run {
                typetag = "木架费用"
                type = getString(R.string.木架费用)
                value = cost_wooden_charge
                valueOption = wooden_charge
                this
            })
            priceList.add(DiffOrderMenuBean().run {
                typetag = "打包费用"
                type = getString(R.string.打包费用)
                value = cost_pack_charge
                valueOption = pack_charge
                this
            })
            priceList.add(DiffOrderMenuBean().run {
                typetag = "综合费用"
                type = getString(R.string.综合费用)
                value = cost_charge
                this
            })

            //总价
            cost_charge?.run {
                val priceText = CurrencyPriceBuilder3().run {
                    price = charge
                    this.priceList = charge_list
                    buildPriceText()
                }
                tv_diff_price.text = String.format(getString(R.string.需付款_数), priceText)
                tv_orderplace_price.text = priceText
                bt_orderplace_submit.isEnabled = true
                priceText
            }


            val diffAdapter = DiffOrderPriceAdapter(priceList)
            priceRecyclerView.run {
                layoutManager = LinearLayoutManager(mActivity)!!
                adapter = diffAdapter
            }
        }

    }

    var waitOrderPayModel: OrderPayModel? = null
    fun startPayResult(resultModel: ResultModel<String>, amount: Double) {
        waitOrderPayModel = OrderPayModel()
        waitOrderPayModel!!.run {
            tradeType = TradeType.Diff
            sn = resultModel.data!!
            payPrice = amount
            Asia5bPayUtils.skipPay(mActivity, this)
        }

    }

    override val isRegisterEventBus: Boolean
        get() = true

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPayEvent(event: PayEvent) {
        pop()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun paySuccess(tradeSerialNo: String?) {
        waitOrderPayModel?.let {
            if (TextUtils.equals(it.sn, tradeSerialNo)) {
                Asia5bPayUtils.checkOrderPayState(it.orderSn) {
                    if (it) {
                        getEventBus().post(AsiaPayEvent(detailModel!!.order_sn))
                        pop()
                    }
                }.joinComposite(mCompositeDisposable)
            }
        }
    }


}